<template>
  <div class="wrap">
    <a-row style="background: #fff; background: #fff; border-radius: 6px">
      <a-col :span="6">
        <div v-show="!showSelect" style="margin-left: 15px; width: auto; height: 500px">
          <div v-if="selectDeptList.length > 0 || selectUserList.length > 0">
            <div v-if="selectDeptList.length > 0">
              <p style="
                  font-size: 12px;
                  color: rgba(23, 26, 29, 0.6);
                  padding-left: 20px;
                ">
                部门
              </p>
              <a-divider style="margin-top: 12px; height: 2px"></a-divider>
              <div v-for="(item, index) in selectDeptList" :key="index" style="margin-top: 10px">
                <span :style="[
                    fontSize,
                    fontColor,
                    paddingLeft,
                    whiteSpace,
                    overflowStyle,
                    backgroundColor,
                    textOverflow,
                  ]" class="orgName" @click="getBySelectId(item)">{{ item.orgName }}</span>
              </div>
            </div>
            <div v-if="selectUserList.length > 0" style="margin-top: 20px">
              <p style="
                  font-size: 12px;
                  color: rgba(23, 26, 29, 0.6);
                  padding-left: 20px;
                ">
                成员
              </p>
              <a-divider style="margin-top: 12px; height: 2px"></a-divider>
              <div v-for="(item, index) in selectUserList" :key="index" style="margin-top: 10px">
                <span :style="[
                    fontSize,
                    fontColor,
                    paddingLeft,
                    whiteSpace,
                    overflowStyle,
                    backgroundColor,
                    textOverflow,
                  ]" class="orgName" @click="getBySelectUser(item)">{{ item.displayName }}</span>
              </div>
            </div>
          </div>
          <div v-if="selectDeptList.length <= 0 && selectUserList.length <= 0">
            <template>
              <a-empty />
            </template>
          </div>
        </div>
        <!-- <a-input-search style="width: 250px;margin: 14px 0 0 20px;" placeholder="请输入搜索的成员" allow-clear
          @search="onSearchGrade" /> -->
        <el-input placeholder="请输入搜索的关键字" style="width: 250px;margin: 14px 0 0 20px;" clearable size="medium"
          v-model="filterText"></el-input>
        <!-- <a-tree style="
            margin: 6px 0 0 10px;
            height: calc(100vh - 250px);
            overflow: scroll;
          " :tree-data="nodeData" :autoExpandParent="true" :defaultExpandParent="true" defaultExpandAll
          :defaultExpandedKeys="[nodeData[0].id]" show-icon @select="onSelect" v-show="showSelect">
          <template #title="{ orgname, id }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ orgname }}</span>
              <template #overlay>
                <a-menu @click="({ key: menuKey }) => onContextMenuClick(id, menuKey)">
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree> -->

        <el-tree style="margin: 6px 0 0 10px;height: calc(100vh - 260px);overflow: scroll;" node-key="id"
          :default-expanded-keys="['1']" highlight-current :filter-node-method="filterNode" :data="nodeData"
          :props="defaultProps1" accordion @node-click="onSelect" ref="tree">
        </el-tree>
      </a-col>
      <div>
        <el-drawer :title="deptName" size="700px" :visible.sync="drawer" :direction="direction"
          :before-close="handleClose">
          <!-- <el-select
            v-model="roelSelectValue"
            filterable
            placeholder="请选择角色"
            style="width: 100px"
          >
            <el-option
              v-for="item in deptRoleInfo"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
          <a-input placeholder="请输入名称" clearable v-model="selectName" style="width: 200px; margin-left: 20px"></a-input>
          <a-button type="primary" style="margin-left: 20px" @click="getDeptUser">搜 索</a-button>
          <div style="margin: 20px;">
            <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark"
              style="width: 100%; max-height: 500px; overflow: auto;" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="ID" width="160">
                <template slot-scope="scope">{{ scope.row.id }}</template>
              </el-table-column>
              <el-table-column prop="displayName" label="名称" width="120">
              </el-table-column>
              <el-table-column prop="department" label="所在部门" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="birthDate" label="出生日期">
              </el-table-column>
              
            </el-table>
          </div>
          <div style="margin: 20px;">
            <span style="padding-left:10px;">定义角色</span>
            <el-checkbox-group v-model="roelSelectValue" style="padding-top:20px;padding-left: 10px;">
              <el-checkbox v-for="(item, index) in deptRoleInfo" :key="index" :label="item.id">{{ item.name
              }}</el-checkbox>
            </el-checkbox-group>
            <el-button style="margin: 20px 10px 10px 10px;" type="primary" size="small"
              @click="addDeptRole()">提交</el-button>
          </div>
        </el-drawer>

        <a-modal v-model="setManagerVisible" :title="deptName" style="height: 300px" @cancel="closeModel">
          <div style="display: inline-block; height: 300px">
            <div style="height: 300px">
              <div :style="{ borderBottom: '1px solid #E9E9E9' }">
                <a-checkbox :indeterminate="indeterminate" v-model="checkAll" @change="onCheckAllChange">全选</a-checkbox>
              </div>
              <br />
              <a-checkbox-group v-model="checkedList" @change="onChange"
                style="width: 200px; height: 100%; overflow: auto;">
                <div v-for="item in plainOptions" :key="item">
                  <a-checkbox :value="item.value" style="height: 50px !important;"><img :src="item.imgUrl" alt="" srcset=""
                      style="border-radius: 5px" />&nbsp;&nbsp;{{ item.label }}</a-checkbox>
                </div>
              </a-checkbox-group>
            </div>
          </div>

          <div style="
              width: 100%;
              height: 518px;
              display: inline-block;
              position: absolute;
              padding-left: 50px;
            ">
            <div>已选择({{ tempList.length }}/9999)</div>
            <div class="dNlTZl" v-for="(item, index) in tempList" :key="index">
              <span>{{ item.displayName }}</span>
            </div>
          </div>

          <template slot="footer">
            <a-button @click="backOut"> 返回 </a-button>
            <a-button key="submit" type="primary" :loading="loading" @click="setDeptZg">
              确定
            </a-button>
          </template>
        </a-modal>
      </div>
      <a-col :span="18" style="
          padding: 10px;
          border-left: 4px solid #edeff2;
          height: calc(100vh - 198px);
        ">
        <div style="margin-top: 10px">
          <div>
            <div style="color: #171a1d;font-weight: 600;font-size: 17px;  height: 30px;">{{ deptName ? deptName : '崇明教育'
            }}</div>
            <div style="display: inline-block; position: absolute; right: 80px" class="set_font_set" v-if="isAdmin">
              <span style="font-weight: 400;white-space: nowrap;text-align: center;cursor: pointer;color: #ff4d4f;
                " @click="setManager()"><a-icon type="user" style="padding-right: 5px" />设置主管</span>
              <span
                style="font-weight: 400;white-space: nowrap;text-align: center;color: #ff4d4f;cursor: pointer;padding-left: 20px;"
                @click="exportUser()"><a-icon type="user" style="padding-left: 5px" />导入用户</span>
              <span
                style="font-weight: 400;white-space: nowrap;text-align: center;color: #ff4d4f;margin-left: 20px;cursor: pointer;">
              </span>
            </div>
          </div>
          <div></div>
          <div style="margin-top: 15px" class="set_font_size">
            <a-input placeholder="请输入用户昵称" style="width:200px;" v-model="selectUserName"></a-input>
            <a-button type="primary" @click="serchUser" style="margin-left:15px">
              搜索
            </a-button>
            <a-button type="primary" @click="addUser" style="margin-left:15px" v-if="isAdmin">
              <a-icon type="user-add" />添加成员
            </a-button>
          </div>
        </div>
        <a-table style="margin-top: 15px" :columns="columns" :data-source="userInfo" bordered class="set_font_size"
          rowKey="id" :pagination="false" :scroll="{ y: tableHeight }">
          <span slot="STATUS" slot-scope="STATUS">
            <span v-if="STATUS == 1">启用</span>
            <span v-else>禁用</span>
          </span>
          <span slot="cz" slot-scope="text, record" @click="editUser(record)">
            <!-- <a>修改用户</a> -->
            <a-button type="link"  v-if="isAdmin">修改用户</a-button>
            <a-button type="link"  @click.stop="removeUser(record)" v-if="isAdmin">移出部门</a-button>
            <!-- <a style="padding-left: 20px" @click.stop="removeUser(record)">移出部门</a> -->
            <a-button type="link"  @click.stop="showDeleteConfirm(record)" v-if="isAdmin">删除用户</a-button>
            <!-- <a @click.stop="showDeleteConfirm(record)" style="padding-left:20px;">删除用户</a> -->
          </span>
        </a-table>
        <a-pagination style="margin: 10px 0" v-model="current" :page-size-options="pageSizeOptions" :total="total"
          show-size-changer :page-size="pageSize" @showSizeChange="onShowSizeChange" @change="pageChange">
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
          </template>
        </a-pagination>
      </a-col>
    </a-row>
    <a-drawer :title="title" placement="right" :closable="true" :visible="visible"
      :headerStyle="{ 'padding-top': '20px' }" width="495px" :after-visible-change="afterVisibleChange" zIndex="2"
      @close="onClose">
      <div>
        <a-modal v-model="modelVisible" title="部门列表" on-ok="handleOk" @cancel="noMoelSelect">
          <template slot="footer">
            <a-button key="back" @click="handleCancel"> 取消 </a-button>
            <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
              确定
            </a-button>
          </template>
          <!-- <a-tree style="min-width: 170px;!important;margin-top:10px;max-height: 400px; overflow-y: auto " ref="nodeTree"
            :tree-data="nodeData" :autoExpandParent="true" :defaultExpandParent="true" :selectedKeys="selectedKeys"
            :replace-fields="replaceFields" :defaultExpandedKeys="[nodeData[0].id]" show-icon @select="selectDept">
          </a-tree> -->

          <el-input placeholder="请输入搜索的关键字" style="width: 250px;margin: 14px 0 0 20px;" clearable size="medium"
          v-model="filterText2"></el-input>
          <el-tree style="margin: 6px 0 0 10px;height: 400px;overflow: scroll;" node-key="id"
          :default-expanded-keys="['1']" highlight-current :filter-node-method="filterNode2" :data="nodeData"
          :props="defaultProps1" accordion @node-click="selectDept" ref="tree">
        </el-tree>
        </a-modal>
      </div>

      <div id="components-form-demo-vuex">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" layout="vertical">
          <a-form-model-item ref="nickName" label="昵称" prop="nickName">
            <a-input v-model="form.nickName" placeholder="请输入昵称" />
          </a-form-model-item>
          <a-form-model-item label="部门" v-show="addOrUpdate == 0">
            <a-input v-model="form.department" readOnly placeholder="点击选择部门" @click="showModal" />
          </a-form-model-item>
          <a-form-model-item label="手机" prop="mobile ">
            <a-input v-model="form.mobile" placeholder="请输入手机号" />
          </a-form-model-item>
          <a-form-model-item ref="userName" label="用户名" prop="userName">
            <a-input v-model="form.userName" placeholder="请输入用户名" />
          </a-form-model-item>
          <a-form-model-item ref="passWord" label="密码" v-show="addOrUpdate == 0">
            <a-input v-model="form.passWord" placeholder="请输入密码" />
          </a-form-model-item>
          <a-form-model-item ref="emial" label="邮箱" prop="emial">
            <a-input v-model="form.emial" placeholder="请输入邮箱" />
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit"> 确 定 </a-button>
            <a-button style="margin-left: 10px" @click="resetForm" v-if="addOrUpdate == 0">
              重 置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-drawer>
  </div>
</template>

<script>
const columns = [
  {
    title: "名称",
    dataIndex: "displayName",
    scopedSlots: { customRender: "name" },
  },

  {
    title: "职位",
    dataIndex: "typeName",
    scopedSlots: { customRender: "type" },
    width: 500
  },
  {
    title: "状态",
    dataIndex: "STATUS",
    scopedSlots: { customRender: "STATUS" },
    width: 70,
  },
  {
    title: "操作",
    dataIndex: "cz",
    scopedSlots: { customRender: "cz" },
    width: 400,
  },
];

const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
  });
}

// 数组对象中查找符合目标的对象
const parseArray = function (objArray, key, value) {
  for (let i in objArray) {
    let element = objArray[i];
    if (typeof element === "object") {
      let result = parseArray(element, key, value);
      if (result) return result;
    } else {
      if (i === key) {
        if (element === value) return objArray;
      }
    }
  }
};

import contacts from "@/api/organizations";
export default {
  name: "index1",
  data() {
    this.cacheData = data.map((item) => ({ ...item }));
    return {
      filterText: '',
      filterText2: '',
      defaultProps1: {
        children: 'children',
        label: 'orgname'
      },
      isAdmin:false,
      getById: 1,
      selectName: "",
      form: {
        nickName: "",
        departmentId: "",
        department: "",
        mobile: "",
        userName: "",
        passWord: "",
        emial: "",
        id: "",
      },
      roelSelectValue: [],
      keyWord: "",
      //color:#171a1d;font-size:14px;padding-left: 20px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
      fontSize: {
        "font-size": "14px",
      },
      fontColor: {
        color: "#171a1d",
      },
      paddingLeft: {
        "padding-left": "20px",
      },
      whiteSpace: {
        "white-space": "nowrap",
      },
      overflowStyle: {
        overflow: "hidden",
      },
      backgroundColor: {},
      textOverflow: {
        "text-overflow": "ellipsis",
      },
      checkedList: [],
      selectUserList: [],
      timer: null,
      selectDeptList: [],
      showSelect: true,
      defaultCheckList: [],
      indeterminate: true,
      checkAll: false,
      plainOptions: [
        { label: "Apple", value: "Apple" },
        { label: "Pear", value: "Pear" },
        { label: "Orange", value: "Orange" },
      ],
      checkedSelected: [],
      setManagerVisible: false,
      modelSelectValue: { name: "", id: "" },
      rules: {
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
        department: [
          { required: true, message: "部门不能为空", trigger: "blur" },
        ],
        // mobile: [
        //   { required: true, message: "部门不能为空", trigger: "change" },
        //   {
        //     min: 11,
        //     max: 11,
        //     message: "请输入正确的手机格式",
        //     trigger: "change",
        //   },
        // ],
        userName: [
          { required: true, message: "用户名不能为空", trigger: "change" },
          { min: 6, max: 14, message: "请输入6-14位字符", trigger: "change" },
        ],
        passWord: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 6,
            max: 50,
            message: "输入有误!密码最少6位字符",
            trigger: "change",
          },
        ],
      },
      data,
      columns,
      editingKey: "",
      deptName: "",
      userInfo: [],
      title: "",
      visible: false,
      deptId: "",
      roleId: "",
      exportUserInfo: [],
      //判断是增加还是修改
      addOrUpdate: 0,
      modelVisible: false,
      replaceFields: {
        title: "orgname",
        key: "id",
        child: "children",
      },
      total: 0,
      current: 1,
      pageSizeOptions: ["10", "20", "30", "40", "50"],
      pageSize: 10,
      pageNo: 1,
      nodeData: [{}],
      codeLine: "",
      selectedKeys: null,
      filterResource: null,
      tempList: [],
      drawer: false,
      tableData: [],
      deptRoleInfo: [],
      multipleSelection: [],
      isRole: false,
      selectUserName: ''
    };
  },
  async created() {
    // 树的获取
    let res = await contacts.getNodeData(); // 获取树节点信息的函数
    this.deptName = res.data.orgname;
    let arr = res.data;
    //arr.push();
    this.nodeData = arr;
  },
  mounted() {
    //this.getDeptUser();
    this.getRole();
    this.getById = 1
    this.getChirld("1"); //初始化表格
  },
  watch: {
    filterText(val) { //监听树节点搜索
      this.$refs.tree.filter(val);
    },
    filterText2(val) { //监听树节点搜索
      this.$refs.tree.filter(val);
    },
    keyWord() {
      if (this.keyWord != "" && this.keyWord != null) {
        this.fd(this.keyWord, 500);
        this.showSelect = false;
      } else {
        this.showSelect = true;
      }
    },
    checkedList: {
      handler(val) {
        this.indeterminate =
          !!val.length && val.length < this.plainOptions.length;
        this.checkAll =
          val.length > 0 && val.length === this.plainOptions.length;
      },
    },
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 420 + "px";
    },
  },
  methods: {
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.getChirld(this.getById);
    },
    serchUser() {
      this.getChirld(this.getById)
    },
    pageChange() {
      this.getChirld(this.getById);
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.getChirld(this.getById);
    },
    filterNode(value, data) { //树节点搜索
      if (!value) return true;
      return data.orgname.indexOf(value) !== -1;
    },
    filterNode2(value, data) { //树节点搜索
      if (!value) return true;
      return data.orgname.indexOf(value) !== -1;
    },
    removeUser(obj) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let arr = [];
          let data = {
            userIds: obj.id.split(","),
            orgId: this.getById,
          };
          contacts.delDeptUser(data).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "移出部门成功",
              });
              this.getChirld(this.getById);
            }
          });
        })
        .catch(() => { });
    },
    addUserDept(data) {
      contacts.addDeptUser(data).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            type: "success",
            message: "导入成功!",
          });
          this.drawer = false;
          this.roelSelectValue = []
          this.getChirld(this.getById);
        }
      });
    },
    addDeptRole() {
      let arr = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        arr.push(this.multipleSelection[i].id);
      }
      let data = {
        userIds: arr,
        orgId: this.getById,
        type: this.roelSelectValue,
      };
      this.addUserDept(data);
    },
    getDeptRole() {
      contacts.getRoleByAddDeptUser().then((res) => {
        this.deptRoleInfo = res.data;
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    exportUser() {
      if (this.deptName == null) {
        this.$message({
          type: "error",
          message: "请选择一个部门",
        });
      } else {
        this.getDeptRole();
        this.drawer = true;
        this.getDeptUser();
      }
    },
    getDeptUser() {
      let data = {
        page: 1,
        size: 20,
        name: this.selectName,
      };
      contacts.getDeptUser(data).then((res) => {
        this.tableData = res.data.data.user;
      });
    },
    getBySelectId(value) {
      this.deptName = value.orgName;
      this.getChirld(value.id);
    },
    getBySelectUser(obj) {
      this.addOrUpdate = 1;
      this.form.nickName = obj.displayName;
      this.form.department = obj.ORGNAME;
      this.form.departmentId = obj.orgId;
      this.form.mobile = obj.MOBILE;
      this.form.userName = obj.USERNAME;
      this.form.emial = obj.EMAIL;
      this.form.passWord = "";
      this.form.id = obj.userId;
      this.visible = true;
    },
    mouseOver() {
      this.backgroundColor = "background-color:black";
    },
    /*输入框防抖 */
    fd(fn, delay) {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        contacts.cySelect(fn).then((res) => {
          this.selectDeptList = res.data[0];
          this.selectUserList = res.data[1];
        });
      }, delay);
    },
    onContextMenuClick(treeKey, menuKey) { },
    showDeleteConfirm(obj) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          contacts.delUser(obj.id).then((res) => {
            if (res.data == "删除成功") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getChirld(this.getById);
            }
          });
        })
        .catch(() => { });
      // var that = this;
      // this.$confirm({
      //   title: "您确定要删除这条数据吗",
      //   content: "此操作可能有风险",
      //   okText: "确定",
      //   okType: "danger",
      //   cancelText: "否",
      //   onOk() {
      //     let orgId = obj.id;
      //     contacts.delUser(orgId).then((res) => {
      //       if (res.data == "删除成功") {
      //         that.$message.success("删除成功");
      //         that.getChirld(that.getById);
      //       }
      //     });
      //   },
      //   onCancel() {},
      // });
    },
    editUser(obj) {
      this.addOrUpdate = 1;
      this.form.nickName = obj.displayName;
      // this.form.department = this.deptName;
      // this.form.departmentId = this.getById;
      this.form.mobile = obj.MOBILE;
      this.form.userName = obj.USERNAME;
      this.form.emial = obj.EMAIL;
      this.form.passWord = "";
      this.form.id = obj.id;
      this.visible = true;
    },
    closeModel() {
      (this.checkedList = []), (this.checkedSelected = []);
    },
    setManager() {
      if (this.getById == "" && this.getById == null) {
        this.$message.error("请选择部门");
      } else if (this.userInfo.length <= 0) {
        this.$message.error("当前部门暂无工作人员");
      } else {
        this.plainOptions = [];
        for (let i = 0; i < this.userInfo.length; i++) {
          this.plainOptions.push({
            label: this.userInfo[i].displayName,
            value: this.userInfo[i].id,
            imgUrl: this.drawLogo(this.userInfo[i].displayName, "微软雅黑"),
          });
        }
        this.checkedList = [];
        this.tempList = [];
        contacts.getZgByOrgId(this.getById).then((res) => {
          for (let index = 0; index < res.data.length; index++) {
            this.checkedList.push(res.data[index].id);
            this.tempList.push({
              displayName: res.data[index].displayName,
              id: res.data[index].id,
            });
          }
        });
        this.setManagerVisible = true;
      }
    },
    backOut() {
      this.setManagerVisible = false;
    },
    onChange() {
      this.tempList = [];

      for (let index = 0; index < this.checkedList.length; index++) {
        let obj = {
          id: this.checkedList[index],
          displayName: this.getOnlyObj(this.checkedList[index]).label,
        };

        this.tempList.push(obj);
      }
    },
    getOnlyObj(id) {
      var obj = this.plainOptions.find(function (obj) {
        return obj.value == id;
      });
      return obj;
    },
    unique(arr) {
      return Array.from(new Set(arr));
    },
    onCheckAllChange(e) {
      this.tempList = [];
      if (e.target.checked) {
        for (let index = 0; index < this.plainOptions.length; index++) {
          let obj = {
            id: this.plainOptions[index].value,
            displayName: this.plainOptions[index].label,
          };
          this.tempList.push(obj);
        }
      }
      this.checkedList = e.target.checked
        ? this.plainOptions.map((item) => item.value)
        : [];
      this.indeterminate = false;
    },
    canclModel(e) {
      this.modelSelectValue = null;
    },
    drawLogo: function (text, font) {
      // 创建画布
      let canvas = document.createElement("canvas"); // 绘制文字环境
      let context = canvas.getContext("2d"); // 设置字体
      context.font = font; // 获取字体宽度
      let width = context.measureText(text).width; // 如果宽度不够 240
      if (width < 240) {
        width = 60;
      } else {
        width = width + 30;
      } // 画布宽度
      canvas.width = 60; // 画布高度
      canvas.height = 40; // 填充白色
      context.fillStyle = "#ff4d4f"; // 绘制文字之前填充白色
      context.fillRect(0, 0, canvas.width, canvas.height); // 设置字体
      context.font = "14px " + font; // 设置水平对齐方式
      context.textAlign = "center"; // 设置垂直对齐方式
      context.textBaseline = "middle"; // 设置字体颜色
      context.fillStyle = "#fff"; // 绘制文字(参数：要写的字，x坐标，y坐标)

      context.fillText(text, canvas.width / 2, canvas.height / 2); // 生成图片信息
      let dataUrl = canvas.toDataURL("image/png");
      // this.imgSrc = dataUrl;

      return dataUrl;
    },
    handleCancel(e) {
      this.form.department = "";
      this.form.departmentId = "";
      this.modelVisible = false;
    },
    setDeptZg() {
      if (this.checkedList <= 0) {
        this.$message.error("最少选择一个人");
      }
      let data = {
        userIds: this.checkedList,
        orgId: this.getById,
      };
      contacts.setDeptZg(data).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("添加成功");
          this.getChirld(this.getById)
          this.setManagerVisible = false;
        }
      });
    },
    showModal() {
      this.modelVisible = true;
    },
    handleOk() {
      this.modelVisible = false;
    },
    showDrawer() {
      this.visible = true;
    },
    onClose() {
      this.addOrUpdate = 0;
      (this.form = {
        nickName: "",
        departmentId: "",
        department: "",
        mobile: "",
      }),
        (this.visible = false);
    },
    noMoelSelect() {
      this.form.department = "";
      this.form.departmentId = "";
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let userInfoDTO = {
            userName: this.form.userName,
            password: this.form.passWord,
            orgId: this.form.departmentId,
            mobile: this.form.mobile,
            nickName: this.form.nickName,
            email: this.form.emial,
            orgName: this.form.department,
            id: "",
          };
          if (this.addOrUpdate == 0) {
            contacts.addUserByOrg(userInfoDTO).then((res) => {
              if (res.data == "添加成功") {
                this.$message.success("添加成功");
                this.getChirld(this.getById);
                this.onClose();
              }
            });
          } else {
            userInfoDTO.id = this.form.id;
            contacts.updateUser(userInfoDTO).then((res) => {
              if (res.data == "修改成功") {
                this.$message.success("修改成功");
                this.getChirld(this.getById);
                this.onClose();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    resetForm() {
      (this.form = {
        nickName: "",
        departmentId: "",
        department: "",
        mobile: "",
        userName: "",
        passWord: "",
        emial: "",
      }),
        this.$refs.ruleForm.resetFields();
    },
    addUser() {
      this.title = "添加成员";
      this.showDrawer();
    },
    // 获取全部节点树
    async GetLimsConfigNode() {
      // this.nodeData = await GetLimsConfigNodeData();
    },
    getAllDept() {
      contacts.getOrganizations().then(() => { });
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    getRole() {
      contacts.getRoleByUser().then((res) => {
        // this.roleId = res.data.data.deptCodeRole[0].code;
        for (let i = 0; i < res.data.data.deptCodeRole.length; i++) {
          if (res.data.data.deptCodeRole[i].code == "t001") {
            this.isAdmin = true;
          }
        }
      });
    },

    edit(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find((item) => key === item.key);
      const targetCache = newCacheData.find((item) => key === item.key);
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key === item.key)
        );
        delete target.editable;
        this.data = newData;
      }
    },
    selectDept(params, e) {
      this.form.department = params.orgname;
      this.form.departmentId =params.id;
      // this.form.department = e.node._props.title;
      // this.form.departmentId = params[0];
    },
    getChirld(params) {
      let data = {
        page: this.current,
        size: this.pageSize,
        orgId: params,
        userName: this.selectUserName
      }
      contacts.getUserList(data).then((res) => {
        this.userInfo = res.data.userInfos;
        this.total = res.data.total
      });
    },
    async onSelect(params, e) {
      this.deptName = params.orgname;
      this.getById = params.id;
      // this.deptName = e.selectedNodes[0].data.props.orgname;
      // this.getById = e.selectedNodes[0].data.props.id;
      contacts.getDeptAuthority(this.getById).then((res) => {
        this.isRole = false;
        for (const index in res.data.data.codes) {
          if (res.data.data.codes[index] == "t001") {
            this.isRole = true;
          }
        }
      });
      this.getChirld(this.getById);
      if (this.filterResource) {
        this.$set(this.filterResource, "scopedSlots", {});
      }
    },
  },
};
</script>

<style lang="less" scoped>
.wrap {
  position: relative;
}

.orgName:hover {
  background-color: #7e868e29;
  cursor: pointer;
}

.set_button_margin_left {
  margin-left: 15px;
}

.set_font_size {
  font-size: 14px;
}
</style>

<style lang="less">
// .ant-checkbox-group-item {
//   display: block;
// }

.ant-drawer-title {
  margin: 0;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  font-size: 14px;
  line-height: 22px;
}

.set_drawer_div {
  margin-top: -15px;
  width: 490px;
  height: 48px;
  font-weight: 500;
  color: #171a1d;
  font-size: 14px;
}
</style>
